package com.yyfax.ph.personal.authority.register;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.form.ClearEditText;
import com.yyfax.common.form.PwdEditText;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.common.tools.SoftKeyboardUtils;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.BuildConfig;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.Constants.TimerTask;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.verifycode.VerifyCodeModel;
import com.yyfax.ph.personal.authority.verifycode.VerifyCodePresenter;
import com.yyfax.ph.web.WebActivity;


public class RegisterActivity extends BaseYYFaxActivity implements RegisterPresenter.View, VerifyCodePresenter.View, TextWatcher {
	private static final String TAG = RegisterActivity.class.getSimpleName();

	private static final int LOADER_ID_REGISTER = 901;
	private static final int LOADER_ID_VERIFY_CODE = 902;

	@BindView(R.id.phone_et)
	ClearEditText mPhoneEt;                      //手机号
	@BindView(R.id.invite_code_et)
	ClearEditText mInviteCodeEt;            //邀请码/公司编码
	@BindView(R.id.edit_text)
	PwdEditText mPwdEt;                   //密码
	@BindView(R.id.verify_code_input_edit_tv)
	ClearEditText mVerifyCodeEt;            //输入验证码
	@BindView(R.id.get_verify_tv)
	TextView mGetVerifyCodeTv;                 //获取验证码
	@BindView(R.id.register_btn)
	Button mRegisterBtn;              //注册按钮
	@BindView(R.id.cb_show)
	CheckBox mCbShow;
	@BindView(R.id.agreement_tv)
	TextView agreementTv;
	@BindView(R.id.invite_code_tip_iv)
	ImageView mInviteCodeTipIv;


	private RegisterPresenter mRegisterPresenter;
	private VerifyCodePresenter mVerifyCodePresenter;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, RegisterActivity.class);
		aty.startActivity(intent);
	}

	private TimerTask timerTask = new TimerTask() {
		@Override
		public void onTime(int time) {
			mGetVerifyCodeTv.setTextColor(getResources().getColor(R.color.color_999999));
			mGetVerifyCodeTv.setText(getString(R.string.count_decrease, Constants.TIME - time));
			mGetVerifyCodeTv.setClickable(false);
		}

		@Override
		public void onEnd() {
			mGetVerifyCodeTv.setText(getString(R.string.re_get_obtain));
			mGetVerifyCodeTv.setClickable(true);
			mGetVerifyCodeTv.setTextColor(getResources().getColor(R.color.color_f05b47));
		}

		public String getKey() {
			return TAG;
		}
	};


	@Override
	public int getContentViewRes() {
		return R.layout.register_activity_layout;
	}

	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(LOADER_ID_REGISTER, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_VERIFY_CODE, null, this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Constants.timerTask = timerTask;
	}

	@Override
	protected void onPause() {
		super.onPause();
		SoftKeyboardUtils.hideKeyboard(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		getSupportLoaderManager().destroyLoader(LOADER_ID_REGISTER);
		getSupportLoaderManager().destroyLoader(LOADER_ID_VERIFY_CODE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Constants.timerTask = null;
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitleVisible(true);
		setTitleLeftVisible(false);
		setTitle(R.string.register);
		mTitleCenter.setTextSize(TypedValue.COMPLEX_UNIT_PX, DensityUtil.dip2px(this, 18));
		mTitleCenter.setTextColor(getResources().getColor(R.color.color_262932));
		mBtnBack.setImageDrawable(getResources().getDrawable(R.drawable.btn_login_back));

		mPhoneEt.addTextChangedListener(this);
		mInviteCodeEt.addTextChangedListener(this);
		mPwdEt.addTextChangedListener(this);
		mVerifyCodeEt.addTextChangedListener(this);
		mCbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
				if (b) {//设置密码可见性
					mPwdEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//设置EditText的内容为可见
				} else {
					mPwdEt.setTransformationMethod(PasswordTransformationMethod.getInstance());//设置EditText的内容为不可见
				}
				mPwdEt.setSelection(mPwdEt.getText().toString().length());//焦点移动到最后
				mPwdEt.postInvalidate();
			}
		});

	}


	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_REGISTER:
				return new PresenterLoader<>(this, new RegisterPresenter.Generator());
			case LOADER_ID_VERIFY_CODE:
				return new PresenterLoader<>(this, new VerifyCodePresenter.Generator());
			default:
				break;
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_REGISTER:
				mRegisterPresenter = (RegisterPresenter) data;
				mRegisterPresenter.attach(this);
				break;
			case LOADER_ID_VERIFY_CODE:
				mVerifyCodePresenter = (VerifyCodePresenter) data;
				mVerifyCodePresenter.attach(this);
				break;
			default:
				break;
		}
	}

	private void inputWatch() {
		String phone = mPhoneEt.getText().toString().trim();
		String verify = mVerifyCodeEt.getText().toString().trim();
		String pwd = mPwdEt.getText().toString().trim();
		String inviteCode = mInviteCodeEt.getText().toString().trim();
		if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(verify) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(inviteCode)) {
			mRegisterBtn.setEnabled(true);
		} else {
			mRegisterBtn.setEnabled(false);
		}
	}

	private boolean checkPhone() {
		String phone = mPhoneEt.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			showToast(R.string.phone_digits_error);
			return false;
		}
		if (!RegexUtil.isMobileNumber(phone)) {
			showToast(R.string.phone_format_error);
			return false;
		}
		return true;
	}

	/***
	 * 新密码必须是字母和数字的组合6到20位
	 */
	private boolean checkPwd() {
		String pwd = mPwdEt.getText().toString().trim();
		if (!RegexUtil.isPassword(pwd)) {
			showToast(R.string.password_format_error_tips);
			return false;
		}
		return true;
	}

	@Override
	public void afterTextChanged(Editable edit) {
		inputWatch();
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		inputWatch();
	}

	@Override
	public RegisterModel.Params getRegisterParams() {
		RegisterModel.Params params = new RegisterModel.Params();
		params.loginName = mPhoneEt.getText().toString();
		params.password = mPwdEt.getText().toString();
		params.invitCode = mInviteCodeEt.getText().toString();
		params.verifyCode = mVerifyCodeEt.getText().toString();
		return params;
	}

	@Override
	public VerifyCodeModel.VerifyCodeParams getVerifyParams(String verifyCodeType) {
		VerifyCodeModel.VerifyCodeParams params = new VerifyCodeModel.VerifyCodeParams();
		params.phone = mPhoneEt.getText().toString();
		params.type = verifyCodeType;
		return params;
	}

	@Override
	public void obtainVerifyCodeSuccess(String verifyCode) {
		//debug模式下自动填充 生产模式下不会进行
		if (BuildConfig.DEBUG) {
			mVerifyCodeEt.setText(verifyCode);
		}

		dismissLoading();
		Constants.timerTask = timerTask;
		Constants.startTimer(TAG);
		showToast(getString(R.string.verification_code_sent));
		mVerifyCodeEt.setFocusable(true);
		mVerifyCodeEt.setFocusableInTouchMode(true);
		mVerifyCodeEt.requestFocus();
		InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		im.showSoftInput(mVerifyCodeEt, 0);
	}

	@Override
	public void obtainVerifyCodeFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void checkVerifyCodeSuccess(String code) {//不调用
	}

	@Override
	public void checkVerifyCodeFailure(String tips) {//不调用
	}


	@Override
	public void registerSuccess(String type) {
		dismissLoading();
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_USER_PHONE, mPhoneEt.getText().toString());
		if ("0".equals(type)) {//0:公司类型 1:邀请码类型
			showTipsDialog(getString(R.string.bind_request_sent), new DialogBase.BottomOneClickListener() {
				@Override
				public void bottomOneClick(DialogBase dialog) {
					showToast(R.string.register_success);
					dialog.dismiss();
					MainActivity.start(RegisterActivity.this, true);
				}
			});
		} else if ("1".equals(type)) {
			showToast(R.string.register_success);
			MainActivity.start(this, true);
		}
	}

	@Override
	public void registerFailure(String tips) {
		CLog.i(TAG, tips);
		dismissLoading();
		showToast(tips);
		if (getString(R.string.verify_code_error).equals(tips)) {
			mVerifyCodeEt.getText().clear();
		}
	}


	@OnClick({R.id.register_btn, R.id.get_verify_tv, R.id.agreement_tv, R.id.invite_code_tip_iv})
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.register_btn:
				if (checkPhone() && checkPwd()) {
					mRegisterPresenter.register();
				}
				break;
			case R.id.get_verify_tv:
				if (checkPhone()) {
					mVerifyCodePresenter.obtainVerifyCode(VerifyCodeModel.VERIFY_CODE_TYPE_USER_REGISTER);
				}
				break;
			case R.id.agreement_tv:
				WebActivity.start(this, getString(R.string.protocol_tx), WebActivity.TYPE_REGISTRATION_AGREEMENT);
				break;
			case R.id.invite_code_tip_iv:
				showTipsDialog(R.string.invite_code_tips);
				break;
				default:
					break;
		}
	}

	/**
	 * TopBar变成白色
	 */
	@Override
	public int getTopBarBackgroundColor() {
		return ContextCompat.getColor(this, R.color.color_fafdff);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO: add setContentView(...) invocation
		ButterKnife.bind(this);
	}
}
